package servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.*;

import connection.DbConnection;

import java.sql.ResultSet;
import java.util.*;



import model.EmailingSystem;
import model.InternalMail;
import model.PollUserImpl;
import bean.Message;
import bean.PollUser;

public class sendMessageServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 555666L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost (request, response);
	}
	
	public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("GBK");
		
		// Error checking
		System.out.println("doPost method of sendMessageServlet reached");
		
		// Get parameters
		String public_private = request.getParameter("public_private");
		String poll = request.getParameter("poll_list");
		String user = request.getParameter("user_list");
		String message = request.getParameter("messageTextInput");
		
		// Error checking
		System.out.println("public private: "+public_private);
		System.out.println("Poll: "+poll);
		System.out.println("User: "+user);
		System.out.println("MEssage: "+message);

		// Create message bean
		Message m = new Message();
		m.setSender(request.getSession().getAttribute("username").toString());
		m.setText(message);

		// Error checking
		System.out.println("Sender: "+m.getSender());
		System.out.println("Message text: "+m.getText());
		
		// Add to database
		DbConnection db = new DbConnection();
		String sql = "Insert into Message (Sender, Text) Values ('"+m.getSender()+"','"+m.getText()+"')";
		System.out.println(sql);
		db.doInsert(sql);
		
		// Get back message id
		String sql2 = "Select max(MessageID) from Message";
		System.out.println(sql2);
		ResultSet rs = db.doSelect(sql2);
		int messageId=-1;
		try {
			while (rs.next()) {
				messageId = rs.getInt(1);
			}
		} catch (Exception e) {
			System.out.println("SQL Exception in sendMessageServlet when getting maxid of messages");
		}
		System.out.println("Messageid: "+messageId);
		
		// Private messages
		if (public_private.equals("private")) {
			System.out.println("private message area");
			

			
			// Add to database receiver list
			String sql3 = "Insert into User_Msg Values('"+user+"',"+messageId+")";
			System.out.println(sql3);
			db.doInsert(sql3);
			
			// Set attributes to success
			request.getSession().setAttribute("Message_send_success","t");
			
		}
		
		// Public Messages
		if (public_private.equals("public")) {
			System.out.println("public messages area");

			// Query database for non-PU users
			String sql4 = "Select username from Poll,User_Poll where User_Poll.PollID=Poll.ID and Poll.Name = '"+poll+"'";
			//String sql4 = " select * from participantlist,poll_participantlist,poll where participantlist.lname=poll_participantlist.lname and poll.id=poll_participantlist.pollid and poll.name='"+poll+"'";
			System.out.println("public people sql: "+sql4);
			ResultSet rs2 = db.doSelect(sql4);
			try {
				while (rs2.next()) {

					// Set user
					user = rs2.getString(1);
					
					// Error checking
					System.out.println("Public message reciever user: "+user);
			
					// Add to database receiver list
					String sql7 = "Insert into User_Msg Values('"+user+"',"+messageId+")";
					System.out.println(sql7);
					db.doInsert(sql7);
				}
			} catch (Exception e) {
				System.out.println("SQL exception in sendMEssageServlet public message section");
			}

			// Query db for PU users
			sql4 = " select user_participantlist.username from user_participantlist,participantlist,poll where user_participantlist.lname=participantlist.lname and user_participantlist.masterusername=participantlist.masterusername and poll.id=participantlist.pollid and poll.name='"+poll+"'";
			System.out.println("public people sql: "+sql4);
			 rs2 = db.doSelect(sql4);
			try {
				while (rs2.next()) {

					// Set user
					user = rs2.getString(1);
					
					// Error checking
					System.out.println("Public message reciever user: "+user);
			
					// Add to database receiver list
					String sql7 = "Insert into User_Msg Values('"+user+"',"+messageId+")";
					System.out.println(sql7);
					db.doInsert(sql7);
				}
			} catch (Exception e) {
				System.out.println("SQL exception in sendMEssageServlet public message section");
			}
			
			
			// Set attributes to success
			request.getSession().setAttribute("Message_send_success","t");
		}

		response.sendRedirect("messages.jsp");
		
	}
	
}
